/*
 * Copyright (c) 2006 - 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.io.*;

/**
 * <p>Project: app2022 - Exam04
 * <p>Powered by webrx On 2022-01-19 17:01:26
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class Exam04 {
    private static final String res = "C:\\ioTest.txt"; //写入的目标文件

    public static void main(String[] args) {
        File file = new File(System.getProperty("user.dir"));//本地项目

        //File file = new File("F:\\原桌面");
        boolean clear = clear(res);//判断目标文件是否存在
        System.out.println(clear ? "删除成功" : "文件不存在,不用删除");
        dir(file);
    }

    public static void dir(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File file1 : files) {
                if (file1.isDirectory()) {
                    dir(file1);
                } else {
                    boolean b = file1.getName().endsWith(".txt");
                    if (b) {//如果是以.txt结尾的文件 读取这个文件
                        sumContext(file1);
                    }
                }
            }
        }
    }

    public static void sumContext(File s) {

        try (BufferedReader bf = new BufferedReader(new FileReader(s));
             BufferedWriter bw = new BufferedWriter(new FileWriter(res, true))) {
            //bf.lines().forEach(System.out::println);
            String s1 = null;
            bw.write(s + "文本的内容如下" + "\n");
            while ((s1 = bf.readLine()) != null) { //输出文本内容
                System.out.println(s1);
                bw.write(s1 + "\n"); //写入目标文件
                bw.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean clear(String s) {
        boolean a = false; //判断文件删除成功与否
        File file = new File(s);
        if (file.delete()) {
            a = true;
        }
        return a;
    }
}
